package controllers.operset;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.File;

import models.Esgridcfg;
import models.Filestore;

import rbac.models.Config;
import rbac.models.Menu;
import rbac.models.Oplog;
import rbac.models.User;
import sun.security.provider.ConfigSpiFile;
import utils.ConfigUtil;
import utils.ImageUtil;
import utils.JpegUtil;
import utils.Md5Util;

import com.et.mvc.JsonView;
import com.et.mvc.View;
import com.et.mvc.MultipartFile;
import com.et.mvc.MultipartRequest;
import com.sun.imageio.plugins.jpeg.JPEG;

import controllers.ApplicationController;

public class ConfigController extends ApplicationController {
     
	public View moveField(int id, String dir) throws Exception {
		User user = (User) rbac.getCurrentUser();
		Esgridcfg item = Esgridcfg.find(Esgridcfg.class, id);
		Esgridcfg target = null;
		if (dir.equals("down")) {
			target = Esgridcfg.findFirst(Esgridcfg.class, "sort>? and uid = ?",
					new Object[] { item.getSort(), user.getLogin() },
					"sort asc");
		} else {
			target = Esgridcfg.findFirst(Esgridcfg.class, "sort<? and uid = ?",
					new Object[] { item.getSort(), user.getLogin() },
					"sort desc");
		}
		if (target != null) {
			Integer tmp = target.getSort();
			target.setSort(item.getSort());
			target.save();
			item.setSort(tmp);
			item.save();
		}
		return new JsonView("success:true");
	}
	
	
	 public View getFieldItems() throws Exception {
		 User user = (User) rbac.getCurrentUser();
		 String cond = " uid = '" + user.getLogin() + "'  ";
	     
	     
	    Map<String,Object> result = new HashMap<String,Object>();
		result.put("total", Long.valueOf(Esgridcfg.count(Esgridcfg.class, cond, null)));
		result.put("rows", Esgridcfg.findAll(Esgridcfg.class, cond, null, "sort"));
	     
	     return new JsonView(result);
	   }
	 
	   
	 
	   public View update(int id, Map<String, Object> params) throws Exception {
		   Esgridcfg item = (Esgridcfg)Esgridcfg.find(Esgridcfg.class, Integer.valueOf(id));
	       item = (Esgridcfg)Esgridcfg.updateModel(item, params);
	       item.save();
	       User user = (User) rbac.getCurrentUser();				
		   Oplog.addMsg(user.getLogin(), user.getName() + "("+getIpAddr(request)+")保存显示字段配置，内容为：" + new JsonView(item));									
			
	       return new JsonView(item);
	   }
	 
	   

	public void index() throws Exception {
		User user = (User) rbac.getCurrentUser();
		long l = Esgridcfg.count(Esgridcfg.class, "uid = '" + user.getLogin() + "' ", null);
		if (l == 0){
		    Esgridcfg.execute(" insert into esgridcfg(title,showtitle,field,sort,width,isshow,format,ishidden,uid ) "+
			     "select title,showtitle,field,sort,width,isshow,format,ishidden,'"+ user.getLogin() +"' from esgridcfg where uid = 'system'  ", null);
		}
					
	}
	
	public View removeConfig() throws Exception
	{
		Map<String,Object> result = new HashMap<String,Object>();
		User user = (User) rbac.getCurrentUser();
		try {
			List<Esgridcfg> esgridcfgs = Esgridcfg.findAll(Esgridcfg.class, "uid = '" + user.getLogin() + "'  ", null);
			Esgridcfg.execute("delete from  Esgridcfg where uid = '" + user.getLogin() + "'  ", null);
			List<Config> configs = Config.findAll(Config.class, "cfgtype = ?" ,new Object[] {  user.getLogin()});
			Config.execute( " delete from configs where  cfgtype = ?",
					new Object[] {  user.getLogin()});
			result.put("success", true);
			Oplog.addMsg(user.getLogin(), user.getName() + "("+getIpAddr(request)+")恢复配置，原配置内容为：" + new JsonView(esgridcfgs) + "\r\n" + new JsonView(configs));									
			
			result.put("msg", "恢复配置成功。");
		} catch (Exception e) {
			result.put("success", false);
			result.put("msg", "恢复配置出错了。");	
		}
		return new JsonView(result);
	}
	
	
	private String uploadFile(User user, MultipartFile file)
			throws Exception {
		String fileName = file.getOriginalFilename();
        
		if (fileName != null && !fileName.equals("")) {
			//检查是不是图片文件
			if (ImageUtil.isImageFile(file) == true)  
			{
				long filesize = file.getSize();
				String maxfilesize = ConfigUtil.getConfig("backpicmaxfilesize");
				long lmaxfilesize = Long.parseLong(maxfilesize);
				if ((lmaxfilesize == 0) || (filesize < lmaxfilesize)){
     			  Filestore store = new Filestore();
	     		  store.setData(file.getBytes());
		     	  store.save();
				  //删除原来的文件	
                  //把值更新到个人参数
		     	 Config cfg = Config.findFirst(Config.class, "cfgcode=? and cfgtype = ?",
							new Object[] { user.getLogin()+"backpicfileid" , user.getLogin()});
					if (cfg == null) {
						cfg = new Config();
					}else{
						if (!cfg.getCfgkeyvalue().equals(""))
						Filestore.execute("delete from Filestores where id = ?", new Object[]{ Integer.parseInt(cfg.getCfgkeyvalue())});
					}
					cfg.setCfgcode(user.getLogin()+"backpicfileid");
					cfg.setCfgkeyname("背景图");
					cfg.setCfgkeyvalue(store.getId().toString());
					cfg.setCfgtype(user.getLogin());
					cfg.save();

			      return "";
				}else{
					return "上传文件太大了，超过最大值（"+maxfilesize+"字节）。";
				}
			}else{
				return "上传文件不是合格的图片文件。";
			}
		}else return "";
	}
	
	public View saveconfig(String themes, String menulayouthidden,String menubuttonhidden,String newfgcolor,String newbgcolor,String updfgcolor,String updbgcolor,
			String ptfgcolor,String ptbgcolor,String expfgcolor,String expbgcolor,String fontsizetwice) throws Exception {
		Map<String,Object> result = new HashMap<String,Object>();
		try {
			User user = (User) rbac.getCurrentUser();
			
			MultipartRequest req = (MultipartRequest) request;
			MultipartFile multipartFile = req.getFile("backimage");
			uploadFile(user, multipartFile);
			
			List<Config> configs = Config.findAll(Config.class, "cfgtype = ?" ,new Object[] {  user.getLogin()});
			
			Config cfg = Config.findFirst(Config.class, "cfgcode=? and cfgtype = ?",
					new Object[] { user.getLogin()+"theme" , user.getLogin()});
			if (cfg == null) cfg = new Config();
			cfg.setCfgcode(user.getLogin()+"theme");
			cfg.setCfgkeyname("主题");
			cfg.setCfgkeyvalue(themes);
			cfg.setCfgtype(user.getLogin());
			cfg.save();
			
			
			cfg = Config.findFirst(Config.class, "cfgcode=? and cfgtype = ?",
					new Object[] { user.getLogin() + "menulayout" , user.getLogin()});
			if (cfg == null) cfg = new Config();
			cfg.setCfgcode(user.getLogin()+"menulayout");
			cfg.setCfgkeyname("菜单布局");
			cfg.setCfgkeyvalue(menulayouthidden);
			cfg.setCfgtype(user.getLogin());
			cfg.save();
			
			cfg = Config.findFirst(Config.class, "cfgcode=? and cfgtype = ?",
					new Object[] { user.getLogin() + "btntype" , user.getLogin()});
			if (cfg == null) cfg = new Config();
			cfg.setCfgcode(user.getLogin()+"btntype");
			cfg.setCfgkeyname("菜单按键");			                   
			cfg.setCfgkeyvalue(menubuttonhidden);
			cfg.setCfgtype(user.getLogin());
			cfg.save();
			
			
			
			cfg = Config.findFirst(Config.class, "cfgcode=? and cfgtype = ?",
					new Object[] { user.getLogin() + "menuselect" , user.getLogin()});
			if (cfg == null) cfg = new Config();
			cfg.setCfgcode(user.getLogin()+"menuselect");
			cfg.setCfgkeyname("菜单选择");			                   
			cfg.setCfgkeyvalue("常用");
			cfg.setCfgtype(user.getLogin());
			cfg.save();
			
			cfg = Config.findFirst(Config.class, "cfgcode=? and cfgtype = ?",
					new Object[] { user.getLogin() + "menuselect" , user.getLogin()});
			if (cfg == null) cfg = new Config();
			cfg.setCfgcode(user.getLogin()+"menuhover");
			cfg.setCfgkeyname("菜单自动打开");			                   
			cfg.setCfgkeyvalue("hover");
			cfg.setCfgtype(user.getLogin());
			cfg.save();
			
			cfg = Config.findFirst(Config.class, "cfgcode=? and cfgtype = ?",
					new Object[] { user.getLogin() + "newfgcolor" , user.getLogin()});
			if (cfg == null) cfg = new Config();
			cfg.setCfgcode(user.getLogin()+"newfgcolor");
			cfg.setCfgkeyname("最新新增前景色");			                   
			cfg.setCfgkeyvalue(newfgcolor);
			cfg.setCfgtype(user.getLogin());
			cfg.save();
			
			cfg = Config.findFirst(Config.class, "cfgcode=? and cfgtype = ?",
					new Object[] { user.getLogin() + "newbgcolor" , user.getLogin()});
			if (cfg == null) cfg = new Config();
			cfg.setCfgcode(user.getLogin()+"newbgcolor");
			cfg.setCfgkeyname("最新新增背景色");			                   
			cfg.setCfgkeyvalue(newbgcolor);
			cfg.setCfgtype(user.getLogin());
			cfg.save();
			
			
			cfg = Config.findFirst(Config.class, "cfgcode=? and cfgtype = ?",
					new Object[] { user.getLogin() + "updfgcolor" , user.getLogin()});
			if (cfg == null) cfg = new Config();
			cfg.setCfgcode(user.getLogin()+"updfgcolor");
			cfg.setCfgkeyname("最新提前前景色");			                   
			cfg.setCfgkeyvalue(updfgcolor);
			cfg.setCfgtype(user.getLogin());
			cfg.save();
			
			cfg = Config.findFirst(Config.class, "cfgcode=? and cfgtype = ?",
					new Object[] { user.getLogin() + "updbgcolor" , user.getLogin()});
			if (cfg == null) cfg = new Config();
			cfg.setCfgcode(user.getLogin()+"updbgcolor");
			cfg.setCfgkeyname("最新提前背景色");			                   
			cfg.setCfgkeyvalue(updbgcolor);
			cfg.setCfgtype(user.getLogin());
			cfg.save();
			
			cfg = Config.findFirst(Config.class, "cfgcode=? and cfgtype = ?",
					new Object[] { user.getLogin() + "ptfgcolor" , user.getLogin()});
			if (cfg == null) cfg = new Config();
			cfg.setCfgcode(user.getLogin()+"ptfgcolor");
			cfg.setCfgkeyname("普通前景色");			                   
			cfg.setCfgkeyvalue(ptfgcolor);
			cfg.setCfgtype(user.getLogin());
			cfg.save();
			
			cfg = Config.findFirst(Config.class, "cfgcode=? and cfgtype = ?",
					new Object[] { user.getLogin() + "ptbgcolor" , user.getLogin()});
			if (cfg == null) cfg = new Config();
			cfg.setCfgcode(user.getLogin()+"ptbgcolor");
			cfg.setCfgkeyname("普通背景色");			                   
			cfg.setCfgkeyvalue(ptbgcolor);
			cfg.setCfgtype(user.getLogin());
			cfg.save();
			
			cfg = Config.findFirst(Config.class, "cfgcode=? and cfgtype = ?",
					new Object[] { user.getLogin() + "expfgcolor" , user.getLogin()});
			if (cfg == null) cfg = new Config();
			cfg.setCfgcode(user.getLogin()+"expfgcolor");
			cfg.setCfgkeyname("过期前景色");			                   
			cfg.setCfgkeyvalue(expfgcolor);
			cfg.setCfgtype(user.getLogin());
			cfg.save();
			
			cfg = Config.findFirst(Config.class, "cfgcode=? and cfgtype = ?",
					new Object[] { user.getLogin() + "expbgcolor" , user.getLogin()});
			if (cfg == null) cfg = new Config();
			cfg.setCfgcode(user.getLogin()+"expbgcolor");
			cfg.setCfgkeyname("过期背景色");			                   
			cfg.setCfgkeyvalue(expbgcolor);
			cfg.setCfgtype(user.getLogin());
			cfg.save();
			
			cfg = Config.findFirst(Config.class, "cfgcode=? and cfgtype = ?",
					new Object[] { user.getLogin() + "fontsizetwice" , user.getLogin()});
			if (cfg == null) cfg = new Config();
			cfg.setCfgcode(user.getLogin()+"fontsizetwice");
			cfg.setCfgkeyname("字体放大倍数");			                   
			cfg.setCfgkeyvalue(fontsizetwice);
			cfg.setCfgtype(user.getLogin());
			cfg.save();
			
			Oplog.addMsg(user.getLogin(), user.getName() + "("+getIpAddr(request)+")保存配置，原配置内容为：" + new JsonView(configs));									
			
			result.put("success", true);
			result.put("msg", "保存配置成功。");
		} catch (Exception e) {
			result.put("success", false);
			result.put("msg", "保存配置出错了。");	
		}
		View view = new JsonView(result);
		view.setContentType("text/plain;charset=utf-8");
		return view;
	}

	

}
